package com.demo.connectdbtest.module.minio.controller;

import com.demo.connectdbtest.module.minio.service.FileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/minio")
@Api(tags = "minio相关接口")
public class MinioController {

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 上传图片到minio
     *
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ApiOperation(value = "图片上传接口")
    public String uploadFile(MultipartFile file) throws IOException {
        try {
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            /*解决多次上传同名文件覆盖问题*/
            // 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            // 获取文件输入流
            InputStream is = file.getInputStream();
            String imgUrl = fileStorageService.uploadImgFile("img", fileName, is);
            return "上传成功";
        } catch (IOException e) {
            return "上传失败";
        }
    }
    //原文链接：https://blog.csdn.net/qq_46921028/article/details/130279107

    @GetMapping("/download")
    @ApiOperation(value = "下载文件接口")
    public String downloadFile(String path) {
        try {

            byte[] bytes = fileStorageService.downLoadFile(path);
            return "下载成功";
        } catch (Exception e) {
            return "下载失败";
        }
    }

    @GetMapping("/listFileName")
    @ApiOperation(value = "查询指定目录下的所有文件名称")
    public List<String> listFileName(String dirPath,Boolean reverse) throws Exception {
        try {
            List<String> list = fileStorageService.listFileName(dirPath,reverse);
            return list;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }


}
